package com.Yukiha.gachamod.network;

import com.Yukiha.gachamod.gachaMenu.client.ClientGachaDataCache;
import net.minecraft.network.FriendlyByteBuf;
import net.minecraftforge.network.NetworkEvent;

import java.util.*;
import java.util.function.Supplier;

/**
 * 客户端接收：同步抽卡模型数据（按稀有度分类）
 */
public class ClientboundSyncGachaDataPacket {

    private final Map<String, Set<String>> data;

    public ClientboundSyncGachaDataPacket(Map<String, Set<String>> data) {
        this.data = data;
    }

    /** 解码构造器（从字节流还原） */
    public static ClientboundSyncGachaDataPacket decode(FriendlyByteBuf buf) {
        int groupCount = buf.readInt();
        Map<String, Set<String>> result = new HashMap<>();

        for (int i = 0; i < groupCount; i++) {
            String rarity = buf.readUtf();
            int size = buf.readInt();
            Set<String> models = new HashSet<>();
            for (int j = 0; j < size; j++) {
                models.add(buf.readUtf());
            }
            result.put(rarity, models);
        }

        return new ClientboundSyncGachaDataPacket(result);
    }

    /** 编码写入字节流 */
    public void encode(FriendlyByteBuf buf) {
        buf.writeInt(data.size());
        for (Map.Entry<String, Set<String>> entry : data.entrySet()) {
            buf.writeUtf(entry.getKey());
            buf.writeInt(entry.getValue().size());
            for (String model : entry.getValue()) {
                buf.writeUtf(model);
            }
        }
    }

    /** 客户端处理逻辑 */
    public void handle(Supplier<NetworkEvent.Context> ctx) {
        ctx.get().enqueueWork(() -> {
            ClientGachaDataCache.updateFromServer(data);
        });
        ctx.get().setPacketHandled(true);
    }
}
